package top.heliming.youyou.service.impl;

import java.io.File;
import java.io.PrintWriter;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import top.heliming.youyou.common.utils.ThreadUtils;
import top.heliming.youyou.service.GoodsHtmlService;
import top.heliming.youyou.service.GoodsService;

/**
 * description: //TODO
 *
 * @author: heliming
 * @date:2019/06/06 上午 1:31
 */
@Service
public class GoodsHtmlServiceImpl implements GoodsHtmlService {
  @Autowired
  private GoodsService goodsService;

  @Autowired
  private TemplateEngine templateEngine;

  @Value("${ly.page.path}")
  private String dest;

  private static final Logger LOGGER = LoggerFactory.getLogger(GoodsHtmlService.class);

  /**
   * 创建html页面
   *
   * @param spuId
   * @throws Exception
   */
  @Override
  public void createHtml(Long spuId) {
    // 创建thymeleaf上下文对象
    Context context = new Context();
      // 获取页面数据
      Map<String, Object> spuMap = this.goodsService.loadModel(spuId);
      // 把数据放入上下文对象
      context.setVariables(spuMap);
      // 创建输出流
      File file = new File(dest + spuId + ".html");
      //如果页面存在，先删除，后进行创建静态页
      if (file.exists()) {
        file.delete();
      }
      try (PrintWriter writer = new PrintWriter(file, "utf-8")) {
        // 执行页面静态化方法
        templateEngine.process("item", context, writer);
      } catch (Exception e) {
        LOGGER.error("【静态页服务】生成静态页面异常", e);
      }
  }

  /**
   * 新建线程处理页面静态化 暂时不用
   * @param spuId
   */
  public void asyncExcute(Long spuId) {
    ThreadUtils.execute(()->createHtml(spuId));
        /*ThreadUtils.execute(new Runnable() {
            @Override
            public void run() {
                createHtml(spuId);
            }
        });*/
  }

  @Override
  public void deleteHtml(Long id) {
    File file = new File(dest, id + ".html");
    file.deleteOnExit();
  }
}
